package com.bmob.lover.ui.fragment.base

import android.media.MediaScannerConnection
import android.net.Uri
import android.view.View
import android.widget.Button
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.luck.picture.lib.entity.LocalMedia
import com.theone.common.util.FileUtils
import com.bmob.lover.R
import com.bmob.lover.app.ext.getTableName
import com.bmob.lover.app.ext.isTestAdmin
import com.bmob.lover.app.util.CacheUtil
import com.bmob.lover.app.util.getCurrentUser
import com.bmob.lover.data.model.bean.BmobBean
import com.bmob.lover.data.model.bean.TheFile
import com.bmob.lover.data.model.bean.User
import com.bmob.lover.viewmodel.base.BaseBmobActionViewModel
import com.bmob.lover.viewmodel.EventViewModel
import com.bmob.lover.viewmodel.UploadFileViewModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.theone.mvvm.base.appContext
import com.theone.mvvm.core.base.fragment.BasePictureSelectorFragment
import com.theone.mvvm.core.base.viewmodel.BaseListViewModel
import com.theone.mvvm.core.app.ext.addFailTipsObserve
import com.theone.mvvm.core.app.util.FileDirectoryManager
import com.theone.mvvm.core.app.util.glide.GlideEngine
import com.theone.mvvm.ext.getAppViewModel
import com.theone.mvvm.ext.qmui.addLeftCloseImageBtn
import com.theone.mvvm.ext.qmui.showSuccessTipsExitDialog
import java.io.File

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-04-30 09:17
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
abstract class BaseFileUploadFragment<T : BmobBean, VM : BaseListViewModel<LocalMedia>, DB : ViewDataBinding> :
    BasePictureSelectorFragment<VM, DB>() {

    // 拿到泛型T的类名
    var mTableName: String = this::class.java.getTableName()

    override fun getViewModelIndex(): Int = 1

    override fun getDataBindingIndex(): Int = 2

    private val mUploadFileVm: UploadFileViewModel by viewModels()
    private val mEventVm: EventViewModel by lazy { getAppViewModel<EventViewModel>() }
    private val mUser:User? by lazy {
        getCurrentUser()
    }

    abstract fun getPublishViewModel(): BaseBmobActionViewModel<T>

    override fun getMaxSelectNum(): Int = 50

    protected open var mSubmit: Button? = null

    abstract fun onPictureNoneSelectClick()
    abstract fun onUploadFileSuccess(files: List<TheFile>)

    abstract fun getTitle(): String
    protected open fun getConfirm(): String = "发布"
    protected open fun getTableName(): String = mTableName
    protected open fun isCompress(): Boolean = true
    protected open fun isDeleteFiles(): Boolean = false

    override fun initView(root: View) {
        super.initView(root)
        addLeftCloseImageBtn(R.drawable.mz_comment_titlebar_ic_close_dark)
        getTopBar()?.run {
            setTitle(getTitle())
            mSubmit = addRightTextButton(getConfirm(), R.id.topbar_right_view)?.apply {
                isEnabled = false
                setOnClickListener {
                    onPublishClick()
                }
            }
        }
    }

    override fun initRecyclerView() {
        super.initRecyclerView()
        getRecyclerView().overScrollMode = View.OVER_SCROLL_NEVER
    }

    override fun createObserver() {
        addLoadingObserve(mUploadFileVm, getPublishViewModel())
        addFailTipsObserve(mUploadFileVm, getPublishViewModel())
        mUploadFileVm.run {
            getResponseLiveData().observe(this@BaseFileUploadFragment, Observer {
                onUploadFileSuccess(it)
            })
        }
        getPublishViewModel().addObserve()
    }

    open fun BaseBmobActionViewModel<*>.addObserve() {
        getBatchSuccessLiveDate().observe(this@BaseFileUploadFragment, Observer {
            onPublishSuccess(it)
        })
        getObjectSuccessLiveDate().observe(this@BaseFileUploadFragment, Observer {
            onPublishSuccess(it.msg)
        })
    }

    protected open fun onPublishSuccess(msg: String) {
        mEventVm.onPublishSuccess(getTableName())
        if (isDeleteFiles()||CacheUtil.isUploadSuccessDeleteFile()) {
            for (file in getSelectList()) {
                File(file.path).let {
                    if (it.exists()) {
                        it.delete()
                        updateLocationFile(it)
                    }
                }
            }
        }
        showSuccessTipsExitDialog(msg)
    }

    /**
     * 通知系统刷新文件
     */
    private fun updateLocationFile(file: File?) {
        try {
            MediaScannerConnection.scanFile(
                    appContext,
                    arrayOf(file?.absolutePath),
                    null
            ) { path: String?, uri: Uri? ->

            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    protected open fun onPublishClick() {
        if(mUser.isTestAdmin()){
            return
        }
        if (getSelectList().size == 0) {
            onPictureNoneSelectClick()
        } else{
            mUploadFileVm.uploadFiles(getSelectList())
        }
    }

    override fun onAddPictureClick() {
        selectImages()
    }

    protected open fun selectImages() {
        PictureSelector.create(this).openGallery(SelectMimeType.ofImage())
            .setMaxSelectNum(getMaxSelectNum())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setSelectedData(getSelectList())
            .forResult(this)
    }

    protected open fun selectVideo() {
        PictureSelector.create(this).openGallery(SelectMimeType.ofVideo())
            .setMaxSelectNum(1)
            .setImageEngine(GlideEngine.createGlideEngine())
            .isDirectReturnSingle(true)
            .setSelectedData(getSelectList())
            .forResult(this)
    }

    override fun onResult(result: ArrayList<LocalMedia>?) {
        super.onResult(result)
        mSubmit?.isEnabled = result?.isNotEmpty() ==  true
    }

    override fun onFetchTransitionConfig(): TransitionConfig = SCALE_TRANSITION_CONFIG

}